package pers.corvey.studyjava.service;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import pers.corvey.studyjava.dao.UserDAO;
import pers.corvey.studyjava.exception.BadRequestException;
import pers.corvey.studyjava.model.User;

@Service
public class UserService {

    @Autowired
    private UserDAO userDAO;
    
    public User login(User user) {
        User realUser = userDAO.findByAccount(user.getAccount());
        if (realUser == null || !realUser.getPassword().equals(user.getPassword())) {
            throw new BadRequestException("账号或密码错误！");
        }
        return realUser;
    }
    
    public User register(User user) {
        if (isAccountExists(user.getAccount())) {
            throw new BadRequestException("该账号已被注册！");
        }
        user.setGmtCreate(new Date());
        user.setGmtModified(new Date());
        userDAO.save(user);
        return user;
        
    }
    
    public boolean isAccountExists(String account) {
        long cnt = userDAO.countByAccount(account);
        if (cnt > 1) {
            //TODO logging
            System.err.printf("数据表User中的（account=%s）出现重复，请检查！", account);
        }
        return cnt > 0;
    }
    
}
